<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { onMounted, reactive, ref } from 'vue'
import { PageData, SelectOption } from '@/api/common/types'
import { CreateOrUpdate, RoleAuthorize } from './components'
import { Edit, Plus, Search, Lock, Unlock, Delete, Trophy } from '@element-plus/icons-vue'
import {
  dictionaryItemName,
  dictionaryItemTag,
  getDictionarySelectOptionList
} from '@/utils/dictionary'
import { ElMessage, ElMessageBox } from 'element-plus'
import { SystemRole, SystemRoleQuery, SystemRoleStatusUpdate } from '@/api/system/role/types'
import {
  getDeleteSystemRoleApi,
  getSystemRoleListApi,
  getUpdateRoleStatusApi
} from '@/api/system/role'

const { t } = useI18n()
let pageData = reactive<PageData<SystemRole>>({
  total: 0,
  size: 10,
  current: 1,
  records: []
})
const getTableData = async () => {
  const res = await getSystemRoleListApi(queryData)
  if (res) {
    pageData.records = res.data.records
    pageData.total = Number(res.data.total)
    pageData.size = Number(res.data.size)
  }
}

const queryData = reactive<SystemRoleQuery>({
  page: 1,
  limit: 10,
  roleName: '',
  roleStatus: ''
})
const listLoading = ref(false)
onMounted(() => {
  getTableData()
})

const createOrUpdateDialogVisible = ref(false)
const systemRole = ref<SystemRole>()
const title = ref('新增角色')
const isCreate = ref(true)
const createRole = () => {
  createOrUpdateDialogVisible.value = true
  title.value = '新增角色'
  isCreate.value = true
  systemRole.value = {
    roleStatus: '1'
  }
}
const updateRole = (role: SystemRole) => {
  createOrUpdateDialogVisible.value = true
  title.value = '编辑角色'
  isCreate.value = false
  systemRole.value = role
}
const roleAuthorizeDialogVisible = ref(false)
const roleAuthorize = (role: SystemRole) => {
  roleAuthorizeDialogVisible.value = true
  systemRole.value = role
}
const roleStatusList = ref<SelectOption[]>()
const getDictionaryList = async () => {
  roleStatusList.value = getDictionarySelectOptionList('status')
}
getDictionaryList()
const lockRole = async (roleId: number) => {
  ElMessageBox.confirm(t('common.lockMessage'), t('common.lockWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      const params = ref<SystemRoleStatusUpdate>({
        roleId: roleId,
        roleStatus: '0'
      })
      const res = await getUpdateRoleStatusApi(params.value)
      if (res.code == '200') {
        ElMessage.success('停用成功')
      } else {
        ElMessage.error('停用失败，请联系管理员')
      }
      await getTableData()
    })
    .catch(() => {})
}

const unlockRole = async (roleId: number) => {
  ElMessageBox.confirm(t('common.unlockMessage'), t('common.unlockWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      const params = ref<SystemRoleStatusUpdate>({
        roleId: roleId,
        roleStatus: '1'
      })
      const res = await getUpdateRoleStatusApi(params.value)
      if (res.code == '200') {
        ElMessage.success('启用成功')
      } else {
        ElMessage.error('启用失败，请联系管理员')
      }
      await getTableData()
    })
    .catch(() => {})
}

const deleteRole = async (roleId: number) => {
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      const res = await getDeleteSystemRoleApi(roleId + '')
      if (res.code == '200') {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error('删除失败，请联系管理员')
      }
      await getTableData()
    })
    .catch(() => {})
}
</script>

<template>
  <ContentWrap>
    <el-form :inline="true" :model="queryData" class="demo-form-inline">
      <el-form-item label="角色名称">
        <el-input v-model="queryData.roleName" placeholder="请输入角色名称" clearable />
      </el-form-item>
      <el-form-item label="角色状态" style="width: 200px">
        <el-select v-model="queryData.roleStatus" placeholder="请选择角色状态">
          <el-option label="全部" value="" />
          <el-option
            v-for="item in roleStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="getTableData"
          ><el-icon class="el-icon--left"><Search /></el-icon>查询</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="createRole"
          ><el-icon class="el-icon--left"><Plus /></el-icon>新增</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="pageData.records"
      v-loading="listLoading"
      border
      style="width: 100%"
      fit
      stripe
      highlight-current-row
    >
      <el-table-column type="selection" align="center" width="55" />
      <el-table-column prop="roleName" align="center" label="角色名称" width="180" />
      <el-table-column prop="roleStatus" align="center" label="角色状态" width="180">
        <template #default="scope">
          <el-tag class="ml-2" :type="dictionaryItemTag('status', scope.row.roleStatus)">
            <span v-if="scope.row.roleStatus">{{
              dictionaryItemName('status', scope.row.roleStatus)
            }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="roleDesc" align="center" label="角色描述" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="300"
      >
        <template #default="{ row }">
          <el-link type="primary" plain @click="updateRole(row)">
            <el-icon class="el-icon--right"><Edit /></el-icon>编辑
          </el-link>
          <el-link
            v-if="row.roleStatus === '1'"
            type="warning"
            style="margin-left: 5px"
            plain
            @click="lockRole(row.roleId)"
          >
            <el-icon class="el-icon--right"><Lock /></el-icon> 停用
          </el-link>
          <el-link
            v-if="row.roleStatus === '0'"
            type="success"
            style="margin-left: 5px"
            plain
            @click="unlockRole(row.roleId)"
          >
            <el-icon class="el-icon--right"><Unlock /></el-icon>启用
          </el-link>
          <el-link type="primary" style="margin-left: 5px" plain @click="roleAuthorize(row)"
            ><el-icon class="el-icon--right"><Trophy /></el-icon>授权</el-link
          >
          <el-link type="danger" style="margin-left: 5px" plain @click="deleteRole(row.roleId)"
            ><el-icon class="el-icon--right"><Delete /></el-icon>删除</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="true"
      v-model:current-page="queryData.page"
      v-model:page-size="queryData.limit"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="pageData.total"
      style="margin-top: 20px"
      v-show="pageData.total > 0"
      @size-change="getTableData"
      @current-change="getTableData"
    />
  </ContentWrap>
  <CreateOrUpdate
    v-if="createOrUpdateDialogVisible"
    v-model="createOrUpdateDialogVisible"
    :role="systemRole"
    :title="title"
    :create="isCreate"
    :refreshList="getTableData"
  />
  <RoleAuthorize
    v-if="roleAuthorizeDialogVisible"
    :role="systemRole"
    v-model="roleAuthorizeDialogVisible"
  />
</template>
